import json
import logging
import os
from datetime import datetime

# 配置日志
def setup_logger():
    """设置日志记录器"""
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    
    # 创建日志文件
    log_dir = 'logs'
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    log_file = os.path.join(log_dir, f'image_processor_{datetime.now().strftime("%Y%m%d")}.log')
    
    # 创建文件处理器
    file_handler = logging.FileHandler(log_file, encoding='utf-8')
    file_handler.setLevel(logging.INFO)
    
    # 创建控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    
    # 创建格式化器并添加到处理器
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)
    
    # 清除所有处理器并添加新的处理器
    if logger.hasHandlers():
        logger.handlers.clear()
    
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    
    return logger

# 初始化日志
logging = setup_logger()

# 语言数据
language_data = {
    "current_language": "zh",
    "zh": {
        "app_title": "图像处理工具",
        "file": "文件",
        "open_original": "打开原始图像",
        "open_grayscale": "打开灰度图像",
        "merge_channels": "合并通道",
        "save_image": "保存图像",
        "language": "语言",
        "exit": "退出",
        "info": "信息",
        "details": "图像详情",
        "edit": "编辑",
        "crop": "裁剪图像",
        "reset": "重置图像",
        "split": "分割",
        "split_channels": "分割通道",
        "channel_title": "通道 {}",
        "save_channel": "保存通道",
        "channel_saved": "通道 {} 已保存至 {}",
        "error": "错误",
        "single_file_error": "合并通道至少需要两个文件",
        "no_image_loaded": "没有加载图像",
        "single_channel_error": "单通道图像无法分割",
        "info_str": "文件名: {}\n总像素: {}\n尺寸: {}\n通道数: {}\n数据类型: {}",
        "no_image_to_be_saved": "没有图像可保存",
        "no_image_to_be_cropped": "没有图像可裁剪",
        "no_crop_area": "请先选择裁剪区域",
        "crop_failed": "裁剪失败",
        "no_reset_image": "没有可重置的图像",
        "confirm_restart": "确认重启",
        "restart_warning": "更改语言需要重启应用程序，是否继续?",
        "success": "成功"
    },
    "en": {
        "app_title": "Image Processing Tool",
        "file": "File",
        "open_original": "Open Original Image",
        "open_grayscale": "Open Grayscale Image",
        "merge_channels": "Merge Channels",
        "save_image": "Save Image",
        "language": "Language",
        "exit": "Exit",
        "info": "Info",
        "details": "Image Details",
        "edit": "Edit",
        "crop": "Crop Image",
        "reset": "Reset Image",
        "split": "Split",
        "split_channels": "Split Channels",
        "channel_title": "Channel {}",
        "save_channel": "Save Channel",
        "channel_saved": "Channel {} saved to {}",
        "error": "Error",
        "single_file_error": "At least two files are required to merge channels",
        "no_image_loaded": "No image loaded",
        "single_channel_error": "Single-channel image cannot be split",
        "info_str": "Filename: {}\nTotal Pixels: {}\nDimensions: {}\nChannels: {}\nData Type: {}",
        "no_image_to_be_saved": "No image to save",
        "no_image_to_be_cropped": "No image to crop",
        "no_crop_area": "Please select a crop area first",
        "crop_failed": "Crop failed",
        "no_reset_image": "No image to reset",
        "confirm_restart": "Confirm Restart",
        "restart_warning": "Changing language requires restarting the application. Continue?",
        "success": "Success"
    }
}

def write_language_data(data, key, value):
    """写入语言数据到配置文件"""
    data[key] = value
    with open('language_config.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

def read_language_data():
    """从配置文件读取语言数据"""
    try:
        with open('language_config.json', 'r', encoding='utf-8') as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        return language_data

# 初始化语言数据
try:
    language_data = read_language_data()
except Exception as e:
    logging.error(f"Failed to read language data: {e}")
    language_data = language_data  # 使用默认语言数据